package com.zis.common;

import com.alibaba.fastjson.JSON;
import com.zis.auction.model.SubFile;
import com.zis.auction.service.ISubFileInter;
import com.zis.core.ResponseEntity;
import com.zis.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Create by wangshen 2018/1/3
 */
@Controller
@RequestMapping("/api/file")
public class FileUploadController {

    @Autowired
    @Qualifier("auctProperties")
    private AuctProperties auctProperties;

    @Autowired
    private ISubFileInter subFileInter;

    private static String diskDir = "";

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public String simpleUpload(@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            return ResponseEntity.createNULLJsonResponse("未选择文件");
        }
        String baseDir = auctProperties.getUploadDir();
        if(baseDir.equals("")){
            return ResponseEntity.createErrorJsonResponse("文件上传配置错误");
        }
        getDiskName(file.getOriginalFilename());
        String filePath = baseDir+diskDir;
        String fileName = file.getOriginalFilename();
        String newFileName = UUID.randomUUID()+"."+fileName.substring(fileName.lastIndexOf(".")+1);
        File newFile = new File(filePath+newFileName);
        if(!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.createErrorJsonResponse("文件上传出错");
        }
        return ResponseEntity.createNormalJsonResponse(diskDir+newFileName);
    }

    /**
     * 业务文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload/{bussId}")
    @ResponseBody
    public String subFile(@RequestParam("file") MultipartFile file, @PathVariable("bussId") String bussId) throws Exception {
        if(file.isEmpty()){
            return ResponseEntity.createNULLJsonResponse("未选择文件");
        }
        String baseDir = auctProperties.getUploadDir();
        if(baseDir.equals("")){
            return ResponseEntity.createErrorJsonResponse("文件上传配置错误");
        }
        String filePath = "/auction/"+bussId+"/";
        String fileName = file.getOriginalFilename();
        String newFileName = UUID.randomUUID()+"."+fileName.substring(fileName.lastIndexOf(".")+1);
        File newFile = new File(baseDir+filePath+newFileName);
        if(!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.createErrorJsonResponse("文件上传出错");
        }
        //保存文件信息到数据库中去
        SubFile subFile = new SubFile();
        subFile.setBussId(bussId);
        subFile.setFileName(fileName);
        subFile.setFileUrl(filePath+newFileName);
        String result = subFileInter.insert(subFile);
        if (!result.equals("error")) {
            return ResponseEntity.createNormalJsonResponse(JSON.parseObject(JSON.toJSONString(subFile)));
        }
        return ResponseEntity.createErrorJsonResponse("文件上传出错");
    }

    /**
     * 根据文件后缀类型建立文件夹
     * @param fileName
     */
    private static void getDiskName(String fileName){
        String fileExtension = fileName.substring(fileName.lastIndexOf(".")+1);
        String date = DateUtil.getDate(new Date(), "yyyyMMdd")+"/";
        if("bmp".equalsIgnoreCase(fileExtension)) {
            diskDir="/images/";
        }
        if("gif".equalsIgnoreCase(fileExtension)) {
            diskDir="/images/";
        }
        if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)  || "png".equalsIgnoreCase(fileExtension) ){
            diskDir="/images/";
        }
        if("html".equalsIgnoreCase(fileExtension)) {
            diskDir="/images/";
        }
        if("txt".equalsIgnoreCase(fileExtension)) {
            diskDir="/files/";
        }
        if("vsd".equalsIgnoreCase(fileExtension)) {
            diskDir="/msfile/";
        }
        if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            diskDir="/msfile/";
        }
        if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            diskDir="/msfile/";
        }
        if("xml".equalsIgnoreCase(fileExtension)) {
            diskDir="/xml/";
        }
        if (diskDir.equals("")) {
            diskDir = "/other/";
        }
        diskDir += date;
    }
}
